package com.fyzk.activity.popupwindow;

import android.content.Context;
import android.graphics.drawable.ColorDrawable;
import android.os.Handler;
import android.os.Message;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.fyzk.activity.app.AppToast;
import com.tyjc.lottery.R;
import com.fyzk.utils.LogUtil;

import java.math.BigDecimal;

/**
 * 自定义键盘
 */
public class POKeyBoardPopupwindow extends PopupWindow implements View.OnTouchListener {

    private Context context;
    private View view;
    private OnKeyBoardListener onKeyBoardListener;

    private TextView title1_tv;
    private TextView title2_tv;
    private TextView multiple_tv;        // 倍数（期数）textview
    private ImageView arrow_iv;            // 收起popup图标
    private LinearLayout keyBoard_top_ll;    // 自定义 倍数（期数）父控件
    private GridView keyboard_gv;
    private KeyBoardAdapter adapter;
    private TextView delete_tv;
    private TextView sure_tv;

    private String multipleStr = "10";
    private int maxMultiple = 9999;        // 最大倍数（期数）
    private int minMultiple = 1;        // 最小倍数（期数）
    private String title1;                // 左侧提示信息（追、投）
    private String title2;                // 右侧提示信息（期、倍）


    String[] keyItemStrs = {"1", "2", "3", "4", "5", "6", "7", "8", "9", "0", "+2", "-2"};

    private int unit;//最小单位值


    public POKeyBoardPopupwindow(Context context, int unit) {
        this(context, 9999, unit);
    }

    public POKeyBoardPopupwindow(Context context, int maxMultiple, int unit) {
        this(context, maxMultiple, "投", "倍", unit);
    }

    public POKeyBoardPopupwindow(Context context, int maxMultiple, String title1, String title2, int unit) {
        this(context, maxMultiple, title1, title2, unit, true);
    }

    public POKeyBoardPopupwindow(Context context, int maxMultiple, String title1, String title2, int unit, boolean isTouchOutside) {
        super(AbsListView.LayoutParams.MATCH_PARENT, AbsListView.LayoutParams.WRAP_CONTENT);
        this.context = context;
        this.view = LayoutInflater.from(context).inflate(R.layout.popup_keyboard, null);
        this.view.setOnTouchListener(this);
        this.view.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
        this.maxMultiple = maxMultiple;
        if (title1 == null || title1.equals("")) {
            title1 = "投";
        }
        this.title1 = title1;
        if (title2 == null || title2.equals("")) {
            title2 = "倍";
        }
        this.title2 = title2;
        initView();
        this.setContentView(view);
        this.setFocusable(isTouchOutside);
        this.setOutsideTouchable(isTouchOutside);
        // 刷新状态
        this.update();
        ColorDrawable dw = new ColorDrawable(0000000000);
        this.setBackgroundDrawable(dw);
        this.setAnimationStyle(R.style.keyboard_anim);
        this.unit = unit;
        keyItemStrs = new String[]{"1", "2", "3", "4", "5", "6", "7", "8", "9", "0", "+" + unit, "-" + unit};
    }


    @Override
    public boolean onTouch(View v, MotionEvent event) {
        int height = view.findViewById(R.id.keyboard_bottom_ll).getTop();

        int y = (int) event.getY();
        if (event.getAction() == MotionEvent.ACTION_UP) {
            if (y < height) {
                dismiss();
            }
        }
        return true;
    }

    private void initView() {
        title1_tv = view.findViewById(R.id.keyboard_title1_tv);
        title2_tv = view.findViewById(R.id.keyboard_title2_tv);
        multiple_tv = view.findViewById(R.id.keyboard_multiple_tv);
        arrow_iv = view.findViewById(R.id.keyboard_arrow_iv);
        keyBoard_top_ll = view.findViewById(R.id.keyboard_top_ll);
        keyBoard_top_ll.setVisibility(View.GONE);
        keyboard_gv = view.findViewById(R.id.keyboard_gv);
//		keyboard_gv.setEnabled(false);
        keyboard_gv.setOverScrollMode(View.OVER_SCROLL_NEVER);
        adapter = new KeyBoardAdapter();
        keyboard_gv.setAdapter(adapter);
        delete_tv = view.findViewById(R.id.keyboard_delete_tv);
        sure_tv = view.findViewById(R.id.keyboard_sure_tv);

        title1_tv.setText(title1);
        title2_tv.setText(title2);

        arrow_iv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dismiss();
            }
        });

        sure_tv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (multipleStr == null || multipleStr.equals("") || multipleStr.equals("0")) {
                    AppToast.getToast().show("最小为" + minMultiple + title2);
                    multipleStr = "" + minMultiple;
                    multiple_tv.setText(multipleStr);
                } else {
                    try {
                        BigDecimal value = new BigDecimal(multipleStr);
                        BigDecimal maxValue = new BigDecimal(maxMultiple);
                        BigDecimal minValue = new BigDecimal(minMultiple);
                        if (value.compareTo(maxValue) > 0) {
                            AppToast.getToast().show("最大为" + maxMultiple + title2);
                            multipleStr = "" + maxMultiple;
                        } else if(value.compareTo(minValue)<0){
                            AppToast.getToast().show("最小为" + minMultiple + title2);
                            multipleStr = "" + minMultiple;
                        }
                    } catch (NumberFormatException e) {
                        LogUtil.e(e.getMessage());
                    }
                    dismiss();
                }
            }
        });

        delete_tv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (multipleStr.length() > 0) {
                    multipleStr = multipleStr.substring(0, multipleStr.length() - 1);
                }
                setValue();
            }
        });

        delete_tv.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(final View v) {
                sleepTime = 250;
                if (v instanceof TextView) {
                    Thread t = new Thread() {
                        @Override
                        public void run() {
                            super.run();
                            while (v.isPressed()) {
                                if (multipleStr.length() > 0) {
                                    multipleStr = multipleStr.substring(0, multipleStr.length() - 1);
                                    handler.sendEmptyMessage(0);
                                }
                                try {
                                    if (sleepTime > minSleepTime) {
                                        sleepTime--;
                                    } else {
                                        sleepTime = minSleepTime;
                                    }
                                    Thread.sleep(sleepTime);
                                } catch (InterruptedException e) {
                                    e.printStackTrace();
                                }
                            }
                        }
                    };
                    t.start();
                }
                return false;
            }
        });

        keyBoard_top_ll.removeAllViews();
        keyBoard_top_ll.addView(getKeyTopView("1" + title2));
        keyBoard_top_ll.addView(getKeyTopView("2" + title2));
        keyBoard_top_ll.addView(getKeyTopView("5" + title2));
        keyBoard_top_ll.addView(getKeyTopView("10" + title2));
        keyBoard_top_ll.addView(getKeyTopView("20" + title2));

    }

    public void hideTop_ll() {
        keyBoard_top_ll.setVisibility(View.GONE);
    }

    long sleepTime = 250;
    long minSleepTime = 10;
    Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            if (msg.what == 0) {
                verifyMultipleStr();
            }
            return false;
        }
    });

    private TextView getKeyTopView(String title) {
        TextView keyBoardView = (TextView) View.inflate(context, R.layout.tv_rr_detail_keyboard_top, null);
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        params.weight = 1;
        params.setMargins(10, 10, 10, 10);
        keyBoardView.setLayoutParams(params);
        keyBoardView.setText(title);

        keyBoardView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (v instanceof TextView) {
                    String text = ((TextView) v).getText().toString();
                    text = text.substring(0, text.length() - 1);
//                    if (text.equals("1") && minMultiple > 1) {
//                        AppToast.getToast().show("最小为" + minMultiple + title2);
//                        return;
//                    }
                    multipleStr = text;
                    multiple_tv.setText(multipleStr);
                }
            }
        });

        return keyBoardView;
    }

    /**
     * 验证是否超过边界值
     */
    private void verifyMultipleStr() {
        if (multipleStr == null || multipleStr.equals("")) {
            multiple_tv.setText("0");
        } else {
            try {
                BigDecimal maxDecimal = new BigDecimal(maxMultiple);
                BigDecimal minValue = new BigDecimal(minMultiple);
                BigDecimal valueDecimal = new BigDecimal(multipleStr);
                if (valueDecimal .compareTo(maxDecimal) > 0) {
                    AppToast.getToast().show("最大为" + maxMultiple + title2);
                    multipleStr = "" + maxMultiple;
                } else if(valueDecimal.compareTo(minValue)<0){
                    AppToast.getToast().show("最小为" + minMultiple + title2);
                    multipleStr = "" + minMultiple;
                }
            } catch (NumberFormatException e) {
                LogUtil.e(e.getMessage());
            }
            multiple_tv.setText(multipleStr);
        }
    }


    private void setValue() {
        if (multipleStr == null || multipleStr.equals("")) {
            multiple_tv.setText("0");
        }
        multiple_tv.setText(multipleStr);
    }


    /**
     * 显示popupWindow
     *
     * @param parent
     */
    public void showPopupWindow(View parent, String multipleStr) {
        this.multipleStr = multipleStr;
        multiple_tv.setText(multipleStr);
        if (!this.isShowing()) {
            if (null != onKeyBoardListener) {
                onKeyBoardListener.popupShow();
            }
            super.showAtLocation(parent, Gravity.BOTTOM, 0, 0);
        } else {
            this.dismiss();
        }
    }

    @Override
    public void dismiss() {
        if (null != onKeyBoardListener) {
            try {
                verifyMultipleStr();
                int integer = Integer.parseInt(multipleStr);
                onKeyBoardListener.popupDismiss(integer);
            } catch (NumberFormatException e) {
                onKeyBoardListener.popupDismiss(1);
            }
        }
        super.dismiss();
    }

    //===== 接口	==========
    public interface OnKeyBoardListener {
        void onItem(int position);

        void popupShow();

        void popupDismiss(int multiple);
    }

    public void setOnKeyBoardListener(OnKeyBoardListener onKeyBoardListener) {
        this.onKeyBoardListener = onKeyBoardListener;
    }

    public void setMinMultiple(int minMultiple) {
        this.minMultiple = minMultiple;
    }

    public void setMaxMultiple(int maxMultiple) {
        this.maxMultiple = maxMultiple;
    }


    class KeyBoardAdapter extends BaseAdapter {
        @Override
        public int getCount() {
            return keyItemStrs.length;
        }

        @Override
        public Object getItem(int position) {
            return keyItemStrs[position];
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            convertView = LayoutInflater.from(context).inflate(R.layout.keyboard_item, null);
            TextView textView = (TextView) convertView.findViewById(R.id.keyboard_item_tv);
            textView.setText(keyItemStrs[position]);
            textView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (v instanceof TextView) {

                        String text = ((TextView) v).getText().toString();
                        if (text.length() == 1) {
                            multipleStr += text;
                        } else {
                            if (text.contains("+")) {
                                int integer = 0;
                                try {
                                    integer = Integer.parseInt(multipleStr);
                                } catch (NumberFormatException e) {

                                }
                                integer += unit;
                                multipleStr = "" + integer;
                            } else if (text.contains("-")) {
                                try {
                                    int integer = Integer.parseInt(multipleStr);
                                    integer -= unit;
                                    multipleStr = "" + integer;
                                } catch (NumberFormatException e) {

                                }
                            }
                        }
                        setValue();
                    }
                }
            });

            textView.setOnLongClickListener(new View.OnLongClickListener() {
                @Override
                public boolean onLongClick(final View v) {
                    sleepTime = 250;
                    if (v instanceof TextView) {
                        Thread t = new Thread() {
                            @Override
                            public void run() {
                                super.run();
                                while (v.isPressed()) {
                                    String text = ((TextView) v).getText().toString();
                                    if (text.contains("+")) {
                                        try {
                                            int integer = Integer.parseInt(multipleStr);
                                            integer += unit;
                                            multipleStr = "" + integer;
                                        } catch (NumberFormatException e) {

                                        }
                                        handler.sendEmptyMessage(0);
                                    } else if (text.contains("-")) {
                                        try {
                                            int integer = Integer.parseInt(multipleStr);
                                            integer -= unit;
                                            multipleStr = "" + integer;
                                        } catch (NumberFormatException e) {

                                        }
                                        handler.sendEmptyMessage(0);
                                    }
                                    try {
                                        if (sleepTime > minSleepTime) {
                                            sleepTime--;
                                        } else {
                                            sleepTime = minSleepTime;
                                        }
                                        Thread.sleep(sleepTime);
                                    } catch (InterruptedException e) {
                                        e.printStackTrace();
                                    }
                                }
                            }
                        };
                        t.start();
                    }
                    return false;
                }
            });
            return convertView;
        }
    }
}
